package com.cqndt.site.controller;

import com.cqndt.site.util.Constant;
import com.cqndt.site.util.RSAUtil;
import com.cqndt.site.util.Result;
import com.cqndt.site.vo.SysUserVo;
import com.cqndt.site.shrio.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;


/**
 * Description:登录
 */
@RestController
@RequestMapping("login")
public class SysLoginController {
    @Autowired
    private Producer producer;

    @ApiOperation("获取验证码")
    @GetMapping("getCaptcha")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @ApiOperation("验证验证码")
    @GetMapping("checkCaptcha")
    public Result checkCaptcha(String code) {
        try {
            String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
            if(!kaptcha.equalsIgnoreCase(code)){
                return new Result().failure(-1,"验证码错误");
            }
        } catch (Exception e) {
            return new Result().failure(-1, e.getMessage());
        }
        return new Result().success();
    }

    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "userName", value = "用户名", defaultValue = "", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "password", value = "加密密码", defaultValue = "", paramType = "query")
    })
    @PostMapping("login")
    public Result login(String userName, String password,HttpServletRequest request) {
        Result result = new Result();
        try {
            //获取私钥
            String privateKey = ShiroUtils.getSession().getAttribute(Constant.PRIVATE_KEY).toString();
            if (privateKey == null) {
                return new Result().failure(404, "请刷新后重新登陆");
            }
            String deStr = RSAUtil.decodeByPrivateKey(password, privateKey);
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName, deStr);
            subject.login(token);
            SysUserVo vo = ShiroUtils.getUserEntity();
            if((vo.getAduitType()&2) == 0){
                return new Result().failure(404,"该用户没有访问权限");
            }
            if(null != request.getSession().getAttribute("periodNum")){
                String periodNum = (String)request.getSession().getAttribute("periodNum");
                vo.setPeriodNum(Integer.parseInt(periodNum));
            }
            result.setData(vo);
            //session验证码和秘钥移除
            ShiroUtils.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
            ShiroUtils.getSession().removeAttribute(Constant.PRIVATE_KEY);
        } catch (UnknownAccountException e) {
            return result.failure(-1, e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return result.failure(-1, "账号或密码不正确");
        } catch (LockedAccountException e) {
            return result.failure(-1, "账号已被禁用,请联系管理员");
        } catch (AuthenticationException e) {
            return result.failure(-1, e.getMessage());
        } catch (Exception e) {
            return result.failure(-1, e.getMessage());
        }
        return result;
    }

    @ApiOperation("退出登录")
    @GetMapping("logout")
    public Result logout() {
        ShiroUtils.logout();
        return new Result().success();
    }

    @ApiOperation("获取公钥和私钥")
    @GetMapping("getKey")
    public Result getKey() {
        RSAUtil rsa = RSAUtil.create();
        String pubKey = rsa.getPublicKey();
        String priKey = rsa.getPrivateKey();
        HashMap<Object, Object> hashMap = new HashMap<>();
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constant.PRIVATE_KEY, priKey);
        hashMap.put("publicKey", pubKey);
        return new Result().success(hashMap);
    }

}
